import os
import os.path

# ui文件所在位置
dir = "../client/pages"

# src文件导入前缀
prefix = "client.src."


# 列出目录下所有ui文件
def listUiFile():
    list = []
    files = os.listdir(dir)
    for filename in files:
        # print(dir + os.sep+ f)
        # print(filename)
        if os.path.splitext(filename)[1] == ".ui":
            list.append(filename)
    return list


# 把扩展名为.ui的文件改为.py
def transPyFile(filename):
    return os.path.splitext(filename)[0] + ".py"


# 对py文件最后仅1行的资源导入进行修改 临时做法 局限性较大
def import_src(filepath):
    lines = open(filepath, "r", encoding='utf-8').read().split("\n")
    if "import " in lines[-2] and "_rc" in lines[-2]:
        py_src = lines[-2].replace("import ", "import " + prefix)
        print(py_src)
        lines[-2] = py_src
        open(filepath, 'w', encoding='utf-8').write("\n".join(lines))


# 调用系统命令把.ui文件换为.py文件
def runMain():
    list = listUiFile()
    for uifile in list:
        pyfile = transPyFile(uifile)
        cmd = 'pyuic5 -o {pyfile} {uifile}'.format(pyfile=os.path.join(dir, pyfile), uifile=os.path.join(dir, uifile))
        # print(cmd)
        os.system(cmd)
        import_src(os.path.join(dir, pyfile))


# 主程序
if __name__ == "__main__":
    runMain()
